'use strict';

/**
 * @ngdoc service
 * @name jgappApp.getDataService
 * @description
 * # getDataService
 * Service in the jgappApp.
 */
angular.module('jgappApp')
    .factory('DataService',function($http, $q, Util) {
        // AngularJS will instantiate a singleton by calling "new" on this function
        var getDataService = {}
        getDataService.getData = function(url, param, headers) {
            var postData = {}
            var delay = $q.defer();
            if (param && param.cache) {
                var data = Util.getLocalInfo(url);
            }
            if (data && data.length > 0 || data && Object.keys(data).length > 0) {
                delay.resolve(data)
                return delay.promise;
            }
            postData.url = url
            postData.dataType = "json"
            postData.method = "POST"
            postData.data = param
            if (headers) {
                postData.headers = headers;
            }
            $http(postData)
                .success(function(data) {
                    if (data.logout) {
                        Util.logout();
                        return;
                    }
                    if (data.success) {
                        if (param && param.cache) {
                            Util.saveLocalInfo(url, data.result || data.dataList || data.data)
                        }
                        delay.resolve(data.result || data.dataList || data.data);
                    } else {
                        delay.reject("获取用户信息出错");
                        Util.Toast(data.result)
                    }
                }).error(function() {
                    Util.Toast("无法连接到服务器")
                    delay.reject("获取用户信息出错");
                });
            return delay.promise;
        }
        return getDataService
    });
